from sgmllib import SGMLParser
from functools import partial

class BasicParser(SGMLParser):    
    """
      Meant to parse OFX formatted data
      Ex of data:
         <tag1>data
         <tag2>data<tag3>more data</tag2>
    """
    def __init__(self, tagFactory):
        SGMLParser.__init__(self)
        self.TagFactory = tagFactory
    
    def reset(self):
        SGMLParser.reset(self)        
        self.sTags = []
        self.specialHandler = None
        self.specialTag = None
        
    def handle_data(self, data):        
        if self.specialHandler is None:    
            self.sTags[-1].value = data
        else:
            self.specialHandler(self.lasttag, data)
        
    #def start_status(self, attrs):
    #    debug = 1
    #    self.tempStatus = self.TagFactory("status", attrs)        
    #    self.specialHandler = getattr(self.tempStatus, "handleChild")
    #    
    #    
    #def end_status(self):
    #    self.sTags[-1].children.append(self.tempStatus)
    #    del self.tempStatus
    #    self.specialHandler = None
    
    def unknown_starttag(self, tag, attrs):
        newTag = self.TagFactory(tag,attrs)
        
        if hasattr(newTag, "handleChild"):
            self.specialHandler = getattr(newTag, "handleChild")
            self.specialTag = newTag
            return 
            
        if self.specialHandler is None:
            self.sTags.append(newTag)        
    
    
    def unknown_endtag(self, tag):
        """A tag was closed, so we have to roll all prior tags up and into
        its starter"""
        
        if self.specialTag is not None and self.specialTag.tag == tag:
            self.sTags[-1].children.append(self.specialTag)
            self.specialTag = None
            self.specialHandler = None
            return
        
        
        subsStack = []
        try:
            while len(self.sTags):
                if(self.sTags[-1].tag != tag):                    
                    subsStack.insert(0,self.sTags.pop())
                else:
                    self.sTags[-1].children += subsStack
                    return
        except IndexError,e:
            self.sTags = subsStack
            return
        
        self.sTags = subsStack